/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 保管费发放记录页面
 */
import React, { Component, Fragment } from 'react';
import { connect } from "dva";
import { Form, Input, Button, Row, Col, DatePicker, Select } from 'antd';
import styles from "../style.less";
import moment from "moment/moment";
import StandardTable from "@/components/StandardTable";
import { debounce } from 'lodash';
import DownLoad from '../components/DownLoad'

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;

@connect(({ loading,dispat,report }) => ({
  dispat,
  report,
  stationing: loading.effects["area/subList"],
  getDistributionRecord: loading.effects["dispat/getDistributionRecord"]
}))
@Form.create()
class DistributionRecord extends Component {
  constructor(props){
    super(props)
    this.state = {
      visible: false,
      mode: ['month', 'month'],
      selectedRowKeys: [],
      showGiveOutDetail: false,
      showGiveOutRecord: false,
      type: null,
      recordValue: {},
      selected_cm_name: null,  //所选驿站名称
      keywords: '',
      page: 1,
      fromValues: {},
      release_end: moment().subtract('months').format('YYYY-MM-DD'),
      release_start: moment().subtract(1, 'months').format('YYYY-MM-DD'),
      confirmLoading: false,
      cm_id: ""
    }
    this.recordColums = [
      {
        title: '发放时间',
        dataIndex: 'create_time',
        key: 'create_time'
      },
      {
        title: '驿站名称',
        dataIndex: 'inn',
        key: 'to_kb_id',
      },
      {
        title: '保管费区间',
        dataIndex: 'region',
        key: 'region'
      },
      {
        title: '发放金额（元）',
        dataIndex: 'send_fee',
        key: 'send_fee',
      },
      {
        title: '核减金额（元）',
        dataIndex: 'deduct_fee',
        key: 'deduct_fee',
      },
    ]
  }

  componentDidMount(){
    const { dispatch } = this.props
    const { release_end, release_start, page } = this.state
    this.getFormValues( values => {
      dispatch({
        type: 'dispat/getDistributionRecord',
        payload: {
          ...values,
          page,
          dl: 0
        }
      })
    })
  }

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format("YYYY-MM-DD"));
        const [start, end] = values.date;
        values.beginDate = start;
        values.endDate = end;
        delete values.date;
      }
      this.setState({
        fromValues: values
      })
      then(values);
    });
  };

  handleSearch = debounce(e => {
    e.preventDefault();
    const { dispatch } = this.props
    
    this.getFormValues((values) => {
      dispatch({
        type : 'dispat/getDistributionRecord',
        payload: {
          ...values,
          page: 1,
          dl:0
        }
      })
    });
  }, 500, {
    leading: true,
    trailing: false
  });

  disabledDate = (current) => {
    return current && current > moment().endOf("day").subtract(0, "days");
  };

  handleTableChange = debounce(pagination => {
    const { dispatch } = this.props
    
    this.setState({page: pagination.current})
    this.getFormValues((values) => {
      dispatch({
        type : 'dispat/getDistributionRecord',
        payload: {
          ...values,
          page: pagination.current,
          dl:0
        }
      })
    });
  }, 500, {
    leading: true,
    trailing: false
  });
  // 驿站下拉
  getStationList = (visible) => {
    if (!visible) return;
    const { dispatch } = this.props;
    dispatch({
      type: "report/getYzList",
      payload: ""
    });
  };

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e, labe) => {
    this.setState({
      cm_id: labe.props.value,
    })
  }

  changeSelect = (value) => {
    if (!value) {
      this.setState({
        cm_id: "",
      })
    }
  }

  render() {
    let { 
      release_end,
      release_start,
      page,
      fromValues,
      cm_id
    } = this.state
    let {
      form: { getFieldDecorator },
      dispat: { distributionRecord },
      getDistributionDetail,
      getDistributionRecord,
      stationing,
      report
    } = this.props
    const yzList = (report && report.yzList) || [];
    return (
      <Fragment>
        <h2>保管费发放记录</h2>
        <Form
          className={styles["search-form"]}
          layout="inline"
          onSubmit={this.handleSearch}
        >
          <Row type='flex' style={{marginBottom:24}}>
            <Col>
              <FormItem>
                {
                  getFieldDecorator('date', {
                    initialValue: [moment(release_start),moment(release_end)]
                  })(
                    <RangePicker
                      placeholder={['开始日期', '结束日期']}
                      format="YYYY-MM-DD"
                      mode={['date','date']}
                      disabledDate={this.disabledDate}
                    />
                  )
                }
              </FormItem>
              <FormItem>
                {getFieldDecorator("cm_id", {
                  initialValue: cm_id,
                })(
                  <Select
                    onDropdownVisibleChange={this.getStationList}
                    filterOption={this.onFilterOperator}
                    placeholder="全部驿站"
                    showSearch
                    allowClear
                    style={{ width: "200px" }}
                    onSelect={this.selectCurrency}
                    onChange={this.changeSelect}
                  >
                    {stationing ? (
                      <Option disabled value="loading">
                        <Spin />
                      </Option>
                    ) : (
                        <Option key="all" value="">
                          全部驿站
                        </Option>
                      )}
                    {yzList.map(({ cm_id, company_name }) => (
                      <Option key={cm_id} value={cm_id}>
                        {company_name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
              <FormItem>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  key="search" 
                  icon="search"
                  loading={getDistributionRecord}
                >查询</Button>
              </FormItem>
              <FormItem>
                <DownLoad 
                  url="/Api/YZ/Fund/settleRecord"
                  dl="1"
                  title="下载"
                  params={fromValues}
                  page={page}
                />
              </FormItem>    
            </Col>
            <Col push={6}>
            <FormItem>
              <Button type="primary" key="search" onClick={this.props.hideRecord} >返回</Button>
            </FormItem>
            </Col>
          </Row>
        </Form>
        <StandardTable    
          rowKey={record => record.id}
          loading={getDistributionRecord}
          data={distributionRecord}
          columns={this.recordColums}
          onChange={this.handleTableChange}
        />
      </Fragment>
    )
  }
}

export default DistributionRecord